package com.sunnay.util;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

public class HttpDao {

    public static String requestHttp(String url,String method,String param,String cookie){
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        try{
            Authenticator.setDefault(new ProxyAuthenticator(CommUtils.proxyUser, CommUtils.proxyPass));
            // 创建代理服务器地址对象
            InetSocketAddress addr = new InetSocketAddress(CommUtils.proxyServer, CommUtils.proxyPort);
            Proxy proxys = new Proxy(Proxy.Type.HTTP, addr);
            URL realUrl = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection(proxys);
            // 设置通用的请求属性
            connection.setRequestMethod(method);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            //connection.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; NT 10.0; vivo X20Plus Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36");
            if(StringUtils.isNotEmpty(cookie))
                connection.setRequestProperty("Cookie", cookie);
            // 建立实际的连接
            connection.connect();
            if(method.equals("POST")){
                out = new PrintWriter(connection.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
            }
            //定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            return result;
        }catch(Exception e){
            System.out.println("异常！"+e.getMessage());
        }finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
            }
        }
        return null;
    }
}
class ProxyAuthenticator extends Authenticator {
    private String user, password;

    public ProxyAuthenticator(String user, String password) {
        this.user     = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password.toCharArray());
    }
}
